package com.example.demo.service.impl;




import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.example.demo.mapper.BorrowMapper;
import com.example.demo.pojo.*;
import com.example.demo.pojo.request.BookRequest;
import com.example.demo.pojo.request.BorrowRequest;
import com.example.demo.pojo.request.CategoryRequest;
import com.example.demo.service.IBookService;
import com.example.demo.service.IBorrowService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.persistence.criteria.CriteriaBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;


@Service
public class BorrowServiceImpl implements IBorrowService {
    @Autowired
    private BorrowMapper borrowMapper;
    //查询全部
    @Override
    public List<Borrow> list() {
        List<Borrow> bookList = borrowMapper.list();
        return bookList;
    }

    //分页查询
    @Override
    public PageInfo<Borrow> page(BorrowRequest borrowRequest) {
        PageHelper.startPage(borrowRequest.getPageNum(),borrowRequest.getPageSize());
        List<Borrow> userList = borrowMapper.page(borrowRequest);
        for (Borrow user : userList) {
            LocalDate returnDate = user.getReturnDate();
            LocalDate now = LocalDate.now();
            //当前日期+1，等于归还日期
            if (now.plusDays(1).isEqual(returnDate)){
                user.setNote("即将到期");
            } else if (now.equals(returnDate)) {
                user.setNote("已到期");
            } else if (now.isAfter(returnDate)) {
                user.setNote("已过期");
            } else {
                user.setNote("正常");
            }
        }
       return new PageInfo<>(userList);
    }

    //回写信息
    @Override
    public Borrow getUser(Integer id) {
        Borrow Borrow = borrowMapper.getUser(id);
        return Borrow;
    }

    //更新数据
    @Override
    public void getIDUser(Borrow Borrow) {
        Borrow.setStatus("已归还");
        borrowMapper.getUserByID(Borrow);
    }

    //添加数据
    @Override
    public void save(Borrow Borrow) {
        Borrow.setCreateTime(new Date());
        //设置归还日期，当前日期+借书天数  ChronoUnit.DAYS枚举类型，加在天的时间段上
        Borrow.setReturnDate(LocalDate.now().plus(Borrow.getDays(), ChronoUnit.DAYS));
        borrowMapper.save(Borrow);
    }

    //删除数据
    @Override
    public void delete(Integer id) {
        borrowMapper.delete(id);
    }

    //删除还书数据
    @Override
    public void deleteBack(Integer id) {
        borrowMapper.deleteBack(id);
    }

    //首页图标接口
    @Override
    public Map<String,Object> getCountByTimeRange(String timeRange) {
        Map<String,Object> map = new HashMap<>();
        Date today = new Date();
        List<DateTime> dateRange;
        switch (timeRange) {
            case "week":
                //DAY_OF_WEEK,设置时间的粒度，即最小单位，设置week为当前时间粒度，
                dateRange= DateUtil.rangeToList(DateUtil.offsetDay(today,-6),today, DateField.DAY_OF_WEEK);
                break;
            case "month":
                dateRange= DateUtil.rangeToList(DateUtil.offsetDay(today,-29),today, DateField.DAY_OF_MONTH);
                break;
            case "month2":
                dateRange= DateUtil.rangeToList(DateUtil.offsetDay(today,-59),today, DateField.DAY_OF_MONTH);
                break;
            case "month3":
                dateRange= DateUtil.rangeToList(DateUtil.offsetDay(today,-89),today, DateField.DAY_OF_MONTH);
                break;
            default:
                dateRange=new ArrayList<>();
        }
        List<String> dateStrRange=datetimeToDateStr(dateRange);
        map.put("data", dateStrRange);//x轴的数据

        //从数据库获取到count，以及date， 如果数据库没有就无法获取
        List<BorrowCountP0> borrowCount = borrowMapper.getCountByTimeRange(timeRange,1);
        List<BorrowCountP0> backCount =borrowMapper.getCountByTimeRange(timeRange,2);

        map.put("borrow", countList(borrowCount,dateStrRange));
        map.put("back", countList(backCount,dateStrRange));
        return map;
    }

    //遍历dateStrRange
    private List<Integer> countList(List<BorrowCountP0> borrowCount, List<String> dateStrRange) {
        List<Integer> list = CollUtil.newArrayList();
        if(CollUtil.isEmpty(borrowCount)){
            return list;
        }
        for (String date : dateStrRange) {
            Integer count = borrowCount.stream().filter(countP0->date.equals(countP0.getDate()))
                    .map(BorrowCountP0::getCount).findFirst().orElse(0);
            list.add(count);
        }
        return list;
    }

    //将datetime的list转换为string的list
    private List<String> datetimeToDateStr(List<DateTime> dateTimeList) {
        ArrayList<String> list = CollUtil.newArrayList();
        if(CollUtil.isEmpty(dateTimeList)) return list;
        for (DateTime dateTime : dateTimeList) {
            //DateUtil.formatDate将日期转换为字符串
            String date=DateUtil.formatDate(dateTime);
            list.add(date);
        }
        return list;
    }

    //还书分页查询
    @Override
    public PageInfo<Back> pageBack(BorrowRequest borrowRequest) {
        PageHelper.startPage(borrowRequest.getPageNum(),borrowRequest.getPageSize());
        List<Back> backs = borrowMapper.pageBack(borrowRequest);
        return new PageInfo<>(backs);
    }

    //添加还书数据
    @Override
    public void saveBack(Back back) {
        back.setCreateTime(new Date());
        back.setRealDate(new Date());
        back.setStatus("已归还");
        borrowMapper.saveBack(back);
    }





}
